package com.ecnu.jiagou.damai.service;

import java.util.List;

import com.ecnu.jiagou.damai.controller.PayController;
import com.ecnu.jiagou.damai.entity.Order;
import com.ecnu.jiagou.damai.entity.Product;
import com.ecnu.jiagou.damai.entity.Ticket;
import com.ecnu.jiagou.damai.mapper.OrderMapper;
import com.ecnu.jiagou.damai.result.Result;
import com.ecnu.jiagou.damai.utils.RedisUtil;
import com.ecnu.jiagou.damai.utils.UUIDUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService {

    private static Logger log = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisUtil redisUtil;

    public Ticket getTicketById(Integer id){

        return orderMapper.getTicketById(id);

    }

    /**
     * 更新表演的座位信息
     * @param ticketid
     * @param rows
     * @param cols
     * @return
     */
    @Transactional
    public boolean updateTicket(String ticketid, String rows, String cols){
        log.info("rows--> "+rows);
        boolean flag = true;
        String[] tickets = ticketid.split(",");
        if(rows.equals("") || cols.equals("")){
            log.info("enter if");
            for(int i = 0; i < tickets.length && flag; ++i){
                Integer id = Integer.parseInt(tickets[i]);
                Ticket ticket = null;
                if(redisUtil.get(("ticket"+ id)) != null){ //缓存中有则从缓存中取
                    ticket = new Ticket();
                    String[] res = redisUtil.get("ticket"+id).toString().split(";");
                    ticket.setTicketid(id);
                    ticket.setSessionid(Long.parseLong(res[0]));
                    ticket.setPrice(Float.parseFloat(res[1]));
                    ticket.setSeat(res[2]);
                    ticket.setCount(Integer.parseInt(res[3]));
                }else{ //缓存没有则从数据库取
                    ticket = orderMapper.getTicketById(Integer.parseInt(tickets[i]));
                }
                int count = ticket.getCount();
                count --;
                ticket.setCount(count);
                redisUtil.set("ticket"+id, ticket.getSessionid()+";"+ticket.getPrice()+";"+ticket.getSeat()+";"+ticket.getCount());
                flag = orderMapper.updateTicket(ticket);
            }
        }else{
            log.info("enter else");
            String[] row = rows.split(",");
            String[] col = cols.split(",");
            for(int i = 0; i < row.length && flag; ++i){
                Integer id = Integer.parseInt(tickets[i]);
                Ticket ticket = null;
                if(redisUtil.get(("ticket"+ id)) != null){ //缓存中有则从缓存中取
                    ticket = new Ticket();
                    String[] res = redisUtil.get("ticket"+id).toString().split(";");
                    ticket.setTicketid(id);
                    ticket.setSessionid(Long.parseLong(res[0]));
                    ticket.setPrice(Float.parseFloat(res[1]));
                    ticket.setSeat(res[2]);
                    ticket.setCount(Integer.parseInt(res[3]));
                }else{ //缓存没有则从数据库取
                    ticket = orderMapper.getTicketById(Integer.parseInt(tickets[i]));
                }
                String seats = ticket.getSeat();
                String[] seat = seats.split(",");
                int count = ticket.getCount();
                int m = Integer.parseInt(row[i]), n = Integer.parseInt(col[i]);
                StringBuilder sb = new StringBuilder(seat[m-1]);
                if(sb.charAt(n) != '1'){
                    return false;
                }
                sb.replace(n, n+1, "2");
                seat[m-1] = sb.toString();
                count --;
                String newseat = StringUtils.join(seat, ",");
                log.info("===newseat===" + newseat);
                log.info("count" + count);
                ticket.setSeat(newseat);
                ticket.setCount(count);
                redisUtil.set("ticket"+id, ticket.getSessionid()+";"+ticket.getPrice()+";"+ticket.getSeat()+";"+ticket.getCount());
                flag = orderMapper.updateTicket(ticket);
            }
        }
        if(flag){
            return true;
        }else{
            return false;
        }
    }

    @Transactional
    public boolean addOrder(Long userid, String ticketid, String personid,String addressid,String rows, String cols){
        String[] tickets = ticketid.split(",");
        String[] persons = personid.split(",");
        boolean flag = true;

        if(rows != null && cols != null && rows != "" && cols != ""){
            String[] row = rows.split(",");
            String[] col = cols.split(",");
            for(int i = 0; i < row.length && flag; ++i){
                Order order = new Order();
                order.setOrderid(UUIDUtil.uuid().toUpperCase());
                order.setTicketid(Integer.parseInt(tickets[i]));
                order.setUserid(userid);
                order.setSeat(row[i]+","+col[i]);
                if(persons.length == 1 && persons[0] == "0"){
                    order.setPersonid(0);
                }else{
                    order.setPersonid(Integer.parseInt(persons[i]));
                }
                order.setAddressid(Integer.parseInt(addressid));

                flag = orderMapper.addOrder(order);
            }
        }else{
            for(int i = 0; i < tickets.length && flag; ++i){
                Order order = new Order();
                order.setOrderid(UUIDUtil.uuid().toUpperCase());
                order.setTicketid(Integer.parseInt(tickets[i]));
                order.setUserid(userid);

                flag = orderMapper.addOrder(order);
            }
        }
        
        if(flag){
            return true;
        }else{
            return false;
        }

    }

    public List<Product> getProduct(Long userid){
        return orderMapper.getProduct(userid);
    }

    public Result<Boolean> deleteOrder(String orderid){
        boolean flag = orderMapper.deleteOrder(orderid);
        return Result.success(flag);
    }
}
